package com.example.shop.goods.dao;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.example.shop.goods.dto.GoodsBrowseInfo;
import com.example.shop.goods.dto.GoodsQueryParam;
import com.example.shop.goods.dto.GoodsTypeFondRatio;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Set;

@Mapper
public interface GoodsBrowseInfoDao {
    public static final String ALL_FIELDS_SQL =
            GoodsBriefInfoDao.ALL_FIELDS_SQL + ",g.purchased_time," + GoodsStyleDao.ALL_FIELDS_SQL;
    @Results(id = "GoodsBrowseInfoResultMap",value = {
            @Result(column = "goods_id",property = "goodsId"),
            @Result(column = "goods_id",property = "goodsDescriptionPicture",
                    many = @Many(select="com.example.shop.mapper.GoodsDescriptionPictureMapper.selectPictureById")),
            @Result(property = "goodsStyleList",
                    many = @Many(resultMap = "com.example.shop.goods.dao.GoodsStyleDao.GoodsStyleDaoResultMap"))
    })
    @Select("<script>" +
            "select " + ALL_FIELDS_SQL +
            "from goods g join r_goods_class gc " +
            "on g.goods_id = gc.goods_id " +
            "where " +
            GoodsQueryParam.QUERY_SQL+
            "</script>")
    List<GoodsBrowseInfo> select(@Param(Constants.WRAPPER) GoodsQueryParam queryParam);

    @ResultMap("GoodsBrowseInfoResultMap")
    @Select("select " + ALL_FIELDS_SQL +
            "from goods g join r_goods_class gc " +
            "on g.goods_id = gc.goods_id "+
            "where g.goods_id = ${goodsId}"
    )
    GoodsBrowseInfo selectById(@Param("goodsId")long goodsId);


    @ResultMap("GoodsBrowseInfoResultMap")
    @Select("<script>" +
            "select * from " +
                "(" +
                "select " + ALL_FIELDS_SQL + ",g.shelf_state," +
                        "DENSE_RANK() over (PARTITION by g.goods_type ORDER BY g.goods_name) RN " +
                "from goods g join r_goods_class gc " +
                "on g.goods_id = gc.goods_id " +
                ") g " +
            "where " +
            "<if test='fondRatioList != null and  !fondRatioList.isEmpty()'>" +
                "<foreach collection='fondRatioList' item='fond' index='index' separator=' or ' open = '(' close = ')'>" +
                    "(" +
                    "goods_type = #{fond.goodsType} and " +
                    "RN &gt;= ${fond.num * (ew.page.pageIndex-1)+1} and " +
                    "RN &lt;= ${fond.num * ew.page.pageIndex} "   +
                    ")"+
                "</foreach> and " +
            "</if>" +
            GoodsQueryParam.QUERY_SQL+
            "</script>")
    //这里我们使用order by rand() 不随机数据，因为效率会低。所以我们在es上随机
    List<GoodsBrowseInfo> fondSelect(@Param(Constants.WRAPPER) GoodsQueryParam queryParam,@Param("fondRatioList") Set<GoodsTypeFondRatio> fondRatioList);

}
